/* 
AMPWatch v2.0 

Copyright 2009 Aruba Networks

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
*/

/* Branding/Localization */
var CONFIGURE_AN_AMP = 'Configure an AMP.';
var NO_RESPONSE_FROM_AMP = 'No response from AMP.';

/* Preferences */
var PREFS = new Object();

function readWidgetPreferences() {
  PREFS.amp = preferences.ampHostname.value;
  PREFS.username = preferences.ampUsername.value;
  PREFS.password = preferences.ampPassword.value;
  PREFS.pollAmpInterval = preferences.pollAmpTimerIntervalPref.value * 60;
  PREFS.signalInterval = preferences.signalTimerIntervalPref.value;
}

function getAmpHostname() {
  return PREFS.amp;
}

function getAmpBaseUrl() {
  return "https://" + PREFS.username +
    ":" + PREFS.password +
    "@" + getAmpHostname();
}

/* Initialize state. */
readWidgetPreferences();

function ampStat(xmlLabel, redOnBad, value) {
  this.xmlLabel = xmlLabel;
  this.redOnBad = redOnBad;
  this.value = value;
}
var AMP_NAME = new ampStat('name', false, getAmpHostname());
var AMP_STATS = new Array(
  new ampStat('new_count', false, '-'),
  new ampStat('up', false, '-'),
  new ampStat('down', true, '-'),
  new ampStat('mismatched', true, '-'),
  new ampStat('rogue', true, '-'),
  new ampStat('alerts', true, '-'),
  new ampStat('client_count', false, '-')
);

if (isUnconfigured()) {
  setError(CONFIGURE_AN_AMP);
  showWidgetPreferences();
} 
draw();
updateBehavior();

/* Functions */

function clearStats() {
  AMP_NAME.value = getAmpHostname();
  for (var s in AMP_STATS) {
    AMP_STATS[s].value = '-';
  }
}

var STATS_XHREQUEST;
function pollAmp() {
  if (isUnconfigured()) {
    return;
  }
  try { 
    STATS_XHREQUEST = new XMLHttpRequest();
    STATS_XHREQUEST.onreadystatechange = handleStatsResponse;
    var url = getAmpBaseUrl() + "/amp_stats";
    STATS_XHREQUEST.open("GET", url, true);
    STATS_XHREQUEST.send(null);
  } catch(e) {
    alert('Stats Request Error: ' + e);
  }
}

function handleStatsResponse() {
  if (STATS_XHREQUEST.readyState == 4) {
    if (STATS_XHREQUEST.status == 200) {
      updateStatsFromXML(STATS_XHREQUEST.responseXML);
    } else {
      clearStats();
      setError(NO_RESPONSE_FROM_AMP);
    }
    draw();
    resetRefreshText();
  }
}

function updateStatsFromXML(xml) {
   try {
     setError('');
     AMP_NAME.value = readStatsValue(xml, AMP_NAME.xmlLabel);
     for (var s in AMP_STATS) {
       AMP_STATS[s].value = readStatsValue(xml, AMP_STATS[s].xmlLabel);
     }
   } catch(e) {
     clearStats();
     setError(e);
   }
}

function readStatsValue(xml, stat) {
    return xml.evaluate("string(amp_stats/" + stat + ")");
}

function updateBehavior() {
  readWidgetPreferences();
  pollAmpTimer.interval = PREFS.pollAmpInterval;
  signalTimer.interval = PREFS.signalInterval;
  if (signalTimer.interval == 0) {
    signalTimer.ticking = false;
  } else {
    signalTimer.ticking = true;
  }
  pollAmp();
  updateWireless();
}

function draw() {
  this[AMP_NAME.xmlLabel + 'Text'].data = AMP_NAME.value;
  for (var s in AMP_STATS) {
    var stat = AMP_STATS[s];
    var textObject = this[stat.xmlLabel + 'Text'];
    textObject.data = stat.value;
    if (stat.redOnBad) {
      textObject.color = (stat.value == 0) ? '#356D9B' : '#FF0000';
    }
  }
}

function setError(msg) {
  errorText.data = msg;
}

function isUnconfigured() {
  if (!getAmpHostname()) {
    return 1;
  }
}

function openAmpUrl(path) {
  if (isUnconfigured()) {
    setError('Configure an AMP.');
    showWidgetPreferences();
  } else {
    var url = 'https://' + getAmpHostname() + path;
    return openURL(url);
  }
}

/* Refresh Button */

var refreshAnimation;
try {
  refreshAnimation = new FadeAnimation(
    refreshText, 0, 500, animator.kEaseOut, refreshAnimationDone
  );
} catch(e) {
}

function resetRefreshText() {
  try { 
    if (refreshAnimation != undefined) { 
      refreshAnimation.kill; 
    }
    refreshText.opacity = 255;
    refreshAnimation = new FadeAnimation(
      refreshText, 0, 500, animator.kEaseOut, refreshAnimationDone
    );
  } catch(e) { }
}
function refreshAnimationDone() {
  refreshText.opacity = 255;
}

function refresh() {
  try { 
    animator.start(refreshAnimation);
  } catch(e) { }
  pollAmp();
}

/* Wireless */

function updateWireless() {
  try {
    if (system.wireless.available && signalTimer.interval) {
      signalFrame.visible = true;
      signalLevel();
    } else {
      signalFrame.visible = false;
    }
  } catch(e) { }
}

var PREVIOUS_SIGNAL_LEVEL = 0;
function signalLevel() {
  var level;
  if (system.wireless.powered) {
    var sig = system.wireless.signal; /* Out of 75. */
    level = Math.min(5, Math.floor(sig / 70 * 5)); 
  } else {
    level = 0;
  }
  if (level != PREVIOUS_SIGNAL_LEVEL) {
     signalImage.src = "images/signal" + level + ".png";
  }
  return level;
}

